export default class {
    constructor(prefix = '') {
        let env = process.env.NODE_ENV;
        let envUrl = {
            // 开发环境
            'development': {
                api: '//bondme.net/api/',
            },
            // 生产环境
            'production': {
                api: '//bondme.com/api/',
            },
        };

        this.base_url = envUrl[env].api;
        this.base_url += prefix;
        this.http = axios.create({
            baseURL: this.base_url,
            withCredentials: false,
            headers: {'X-Requested-With': 'XMLHttpRequest'},
        });

        this.http.interceptors.request.use((config) => {
            if (SessionStore.get('loginMesg')) {
                config.headers['x-access-token'] = SessionStore.get('loginMesg').token;
            }
            return config;
        });

        this.http.interceptors.response.use(
            (response) => {
                if (!response.data.status) {
                    return response.data;
                }

                if (response.data.status.code === 0) {
                    return response.data.data;
                }
                if (response.data.status.code !== 0) {
                    this.errorHandle(response.data);
                    if (response.data.status.msg) {
                        Ele.$message.error(response.data.status.msg);
                        return Promise.reject(response.data);
                    }
                    return Promise.reject(response.data);
                }
            },
            (error) => {
                if (error.response && error.response.status > 200) {
                    return this.httpErrorHandle(error);
                }
                Ele.$message.error(error.message);
                return Promise.reject(error);
            }
        );
    }

    errorHandle(data) {
        this.error = data;
        for (let error of this.errors()) {
            if (error.code != data.errorCode) {
                continue;
            }
            if (error.message) {
                Ele.$message.error(error.message);
                // continue
            }
            if (typeof error.method == 'function') {
                error.method();
            }
        }
    }

    errors() {
        return [{}];
    }
}
